package com.yvan.dsf;

import com.alibaba.dubbo.rpc.RpcContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * DsfDebugFilterAutoConfiguration
 *
 * @author edifier.will
 */

@Configuration
public class DsfDebugFilterAutoConfiguration {

    public static final String DEBUG_KEY = "DEBUGGER";

    @Bean
    public FilterRegistrationBean debugFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new DebugFilter());
        registration.addUrlPatterns("/*");
        registration.setName("DebugFilter");
        registration.setOrder(1);
        return registration;
    }

    public class DebugFilter implements Filter {
        @Override
        public void destroy() {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {

            if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
                chain.doFilter(request, response);
                return;
            }

            String debugger = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (cookies != null && cookies.length > 0) {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    String cookName = cookie.getName();
                    if (cookName != null && cookName.equals(DEBUG_KEY)) {
                        debugger = cookie.getValue();
                    }
                }
            }
            if (!StringUtils.isEmpty(debugger)) {
                RpcContext.getContext().setAttachment("debugger", debugger);
            }
            chain.doFilter(request, response);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }
}
